package com.leoman.plz_p.presenter;


import com.leoman.plz_p.interfaces.LoginView;
import com.leoman.plz_p.module.api.LoginApi;
import com.leoman.plz_p.module.bean.BaseData;
import com.leoman.plz_p.module.bean.CodeBean;
import com.leoman.plz_p.module.bean.MapData;
import com.leoman.plz_p.module.bean.RefreshUser;
import com.leoman.plz_p.subscriber.ResponseSubscriber;
import com.leoman.plz_p.utils.UserHelper;
import com.leoman.plz_p.utils.authority.AuthorityContext;

import cn.com.corelib.api.ResponseTransformer;
import cn.com.corelib.base.BasePresenter;
import cn.com.corelib.utils.ToastMgr;
import cn.com.corelib.utils.rxbus.RxBus;

public class LoginPresenter extends BasePresenter<LoginView> {

    private LoginApi loginApi;

    @Override
    protected void onViewAttach() {
        super.onViewAttach();
        loginApi=getApi(LoginApi.class);
    }

    public void login(String studentId, String password, String captcha){
        if (isEmpty(studentId)){
            ToastMgr.show("请输入学籍号");
            return;
        }
        if (isEmpty(password)){
            ToastMgr.show("请输入账户密码");
            return;
        }
        if (isEmpty(captcha)){
            ToastMgr.show("请输入验证码");
            return;
        }
        view.showLoading();
        loginApi.login(studentId,password,captcha, UserHelper.getmDevID()).compose(new ResponseTransformer<>(this.<BaseData<MapData>>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData<MapData>>(view) {
                    @Override
                    public void success(BaseData<MapData> mapDataBaseData) {
                        AuthorityContext.getContext().loggedIn();
                        UserHelper.saveUser(mapDataBaseData.data.user);
                        view.loginSuccess();
                        RxBus.getDefault().send(new RefreshUser());
                    }
                });
    }

    public void getCode(){
        loginApi.getCode(UserHelper.getmDevID()).compose(new ResponseTransformer<>(this.<BaseData<CodeBean>>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData<CodeBean>>(view) {
                    @Override
                    public void success(BaseData<CodeBean> mapDataBaseData) {
                       view.getCodeSuccess(mapDataBaseData.data.getCaptcha());
                    }
                });
    }

    @Override
    public void onStart() {
        getCode();
    }
}